﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;


namespace Aribaccio.Core
{
    /// <summary>
    /// HttpClient服务类
    /// </summary>
    public class HttpClientService : IHttpClientService, ILifeTimeTransient
    {
        private IHttpClientFactory HttpClientFactory;
        /// <summary>
        /// 带参构造函数[注入]
        /// </summary>
        /// <param name="argHttpClientFactory">HttpClient工厂对象</param>
        public HttpClientService(IHttpClientFactory argHttpClientFactory)
        {
            this.HttpClientFactory = argHttpClientFactory;
        }

        /// <summary>
        /// HttpClient的Post方法
        /// [适用WebService]
        /// </summary>
        /// <param name="argUrl">Url地址</param>
        /// <param name="argContent">HttpContent内容对象</param>
        /// <returns>读取数据字符串</returns>
        public string PostAsyncToHttpContent(string argUrl, HttpContent argContent)
        {
            string result = string.Empty;
            try
            {
                using (HttpClient client = HttpClientFactory.CreateClient())
                {
                    using (Task<HttpResponseMessage> response = client.PostAsync(argUrl, argContent))
                    {
                        //确保成功状态
                        response.Result.EnsureSuccessStatusCode();
                        if (response.Result.StatusCode == HttpStatusCode.OK)
                        {
                            result = response.Result.Content.ReadAsStringAsync().Result;
                        }
                    }
                }
            }
            catch (Exception)
            {
                result = null;
            }
            return result;
        }
        /// <summary>
        /// HttpClient的Post方法
        /// [适用WebService]
        /// </summary>
        /// <param name="argUrl">Url地址</param>
        /// <param name="argDictParams">参数字典</param>
        /// <returns>读取数据字符串</returns>
        public string PostAsyncToHttpContentParams(string argUrl, Dictionary<string, string> argDictParams)
        {
            //将参数转化为HttpContent
            HttpContent httpContent = new FormUrlEncodedContent(argDictParams);
            //请求并返回数据
            return this.PostAsyncToHttpContent(argUrl, httpContent);
        }

        /// <summary>
        /// HttpClient的Post方法
        /// [适用RESTful风格]
        /// </summary>
        /// <param name="argUrl">Url地址</param>
        /// <param name="content">Json序列化字符串</param>
        /// <returns>读取数据字符串</returns>
        public string? PostAsyncToStringContent(string argUrl, string? argJsonContent = null)
        {
            string? result = null;
            try
            {
                using (HttpClient httpClient = HttpClientFactory.CreateClient())
                {
                    //创建字符串连接内容
                    StringContent? content = !string.IsNullOrEmpty(argJsonContent)
                        ? new StringContent(argJsonContent, Encoding.Default, "application/json") : null;
                    //定义连接方式
                    httpClient.DefaultRequestHeaders.Add("Method", "Post");
                    //异步等待请求结果
                    using (Task<HttpResponseMessage> response = httpClient.PostAsync(argUrl, content))
                    {
                        response.Result.EnsureSuccessStatusCode();
                        if (response.Result.StatusCode == HttpStatusCode.OK)
                        {
                            result = response.Result.Content.ReadAsStringAsync().Result;
                        }
                    }
                    ////异步等待请求结果
                    //var response = await httpClient.PostAsync(argUrl, content);
                    //if (response != null && response.IsSuccessStatusCode)
                    //{
                    //    result = response.Content.ReadAsStringAsync().Result;
                    //}
                }
            }
            catch (Exception)
            {
                result = null;
            }
            return result;
        }
        /// <summary>
        ///  HttpClient的Post方法
        /// [适用RESTful风格]
        /// </summary>
        /// <typeparam name="T">泛型模型</typeparam>
        /// <param name="argUrl">Url地址</param>
        /// <param name="argItems">泛型对象</param>
        /// <returns>读取数据字符串</returns>
        public string? PostAsyncToStringContentModel<T>(string argUrl, T argItem)
        {
            //对象集合序列化Json字符串
            string? jsonContent = argItem.ToJsonString();
            if (string.IsNullOrEmpty(jsonContent)) { return null; }
            //请求并返回数据
            return this.PostAsyncToStringContent(argUrl, jsonContent);
        }
        /// <summary>
        ///  HttpClient的Post方法
        /// [适用RESTful风格]
        /// </summary>
        /// <typeparam name="T">泛型模型</typeparam>
        /// <param name="argUrl">Url地址</param>
        /// <param name="argItems">泛型对象集合</param>
        /// <returns>读取数据字符串</returns>
        public string? PostAsyncToStringContentModel<T>(string argUrl, List<T> argItems)
        {
            //对象集合序列化Json字符串
            string? jsonContent = argItems.ToJsonString();
            if (string.IsNullOrEmpty(jsonContent)) { return null; }
            //请求并返回数据
            return this.PostAsyncToStringContent(argUrl, jsonContent);
        }
    }
}
